package utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.math.BigDecimal;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.io.IOUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class StaticUtils {
	public static void mustExitErrorMsg(String body, int exitCode){
		errorMsg(body);
		System.exit(exitCode);
	}
	
	public static void errorMsg (String body){
		JOptionPane.showMessageDialog(null, body, "Error", JOptionPane.ERROR_MESSAGE);
	}
	
	public static int[] splitToComponentTimes(long longVal) //BigDecimal biggy
	{
	    //long longVal = biggy.longValue();
	    int hours = (int) longVal / 3600;
	    int remainder = (int) longVal - hours * 3600;
	    int mins = remainder / 60;
	    remainder = remainder - mins * 60;
	    int secs = remainder;

	    int[] ints = {hours , mins , secs};
	    return ints;
	}
	
	public static Document loadXMLFromFile(File xml) throws ParserConfigurationException, SAXException, IOException{
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		return dBuilder.parse(xml);
	}
	
    public static Document loadXMLFromString(String xml) throws Exception
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        return builder.parse(is);
    }
    
    public static byte[] getStdOutByteArr(String command) throws Exception{
    	String[] arr = {command};
		return getStdOutByteArr(arr);

    }
    
    public static byte[] getStdOutByteArr(String[] command) throws Exception{
    	ProcessBuilder ps=new ProcessBuilder(command);
    	
    	Process pr = null;
		try {
			pr = ps.start();
		} catch (IOException e1) {
			e1.printStackTrace();
		}  
    	
    	BufferedReader err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
    	
    	System.out.println(streamToStr(err)); //verbose err stream
    	try {
			pr.waitFor();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return IOUtils.toByteArray(pr.getInputStream());

    }
    
    public static String getStdOutStr(String command){
    	ProcessBuilder ps=new ProcessBuilder(command);
    	
    	Process pr = null;
		try {
			pr = ps.start();
		} catch (IOException e1) {
			e1.printStackTrace();
		}  
    	
    	BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    	//BufferedReader err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
    	
    	BufferedReader err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
    	
    	//System.out.println(streamToStr(in));
    	try {
			pr.waitFor();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	return streamToStr(in);
    }
    
    public static String padWithQuotes(String s){
    	return "\""+s+"\"";
    }
    
    public static String implode(String[] str, String delimiter){
    	StringBuilder sb = new StringBuilder();
    	for (int i = 0; i < str.length; i++) {
    		if(str[i] != null && !str[i].equals("") && !str[i].equals(" ")){
	    	    sb.append(str[i]);
	    	    if (i != str.length - 1) {
	    	        sb.append(delimiter);
	    	    }
    		}
    	}
    	return sb.toString();
    }
    
    private static String streamToStr(BufferedReader stream){
    	String line;
        String outString="";
		try {
			while ((line = stream.readLine()) != null) {
				outString += line;
				//System.out.println(line); //verbose xml file
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return outString;
    }
    
    public static String getMydocumentsDirWinOnly(){
    	
    	/* Older version - only if new will fail
    	 
    	String myDocuments = null;
    	String s = null;

    	try {
    	    Process p =  Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal");
    	    p.waitFor();

    	    InputStream in = p.getInputStream();
    	    byte[] b = new byte[in.available()];
    	    in.read(b);
    	    in.close();

    	    myDocuments = new String(b);
    	    String[] myDocumentsArr = myDocuments.split("\n");
    	    for (String x : myDocumentsArr){
    	    	if (x.contains(":\\")){
    	    		s = x;
    	    		break;
    	    	}
    	    }
    	    
    	    for (int i=0; i<s.length(); i++){
    	    	if (s.indexOf(":\\") == i){
    	    		s = s.substring(i-1);
    	    		break;
    	    	}
    	    }
  	    		   	    
    	} catch(Throwable t) {
    	    t.printStackTrace();
    	}
    	
    	//System.out.println(s);
    	
    	//return s.trim();
    	 
    	 
    	 */
    	
    	//better way witout using registry
    	
    	return new JFileChooser().getFileSystemView().getDefaultDirectory().toString();
    }
    
//    private static byte[] streamToByteArr(BufferedReader stream){
//    	Byte line;
//        String outString="";
//		try {
//			while ((line = stream.read()) != null) {
//				outString += line;
//				//System.out.println(line);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return outString;
//    }

}
